package cn.hfatec.shms.system.user.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.organization.model.Organization;
import cn.hfatec.shms.system.organization.model.OrganizationParams;
import cn.hfatec.shms.system.organization.service.OrganizationService;
import cn.hfatec.shms.system.role.model.RoleParams;
import cn.hfatec.shms.system.role.service.RoleService;
import cn.hfatec.shms.system.user.model.ModifyPassword;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.system.user.model.UserParams;
import cn.hfatec.shms.system.user.service.UserService;
import cn.hfatec.shms.system.userRole.service.UserRoleService;
import com.google.common.base.Optional;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/system/user")
public class UserAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "UserService")
    private UserService userService;

    @Resource(name = "UserRoleService")
    private UserRoleService userRoleService;

    @Resource(name = "RoleService")
    private RoleService roleService;

    @Resource(name = "OrganizationService")
    private OrganizationService organizationService;


    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(UserParams userParams, Page page, Model model) {

        Table table = userService.queryUserTable(userParams, page);
        model.addAttribute("usersTable", table);
        model.addAttribute("userParams", userParams);
        model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
        model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
        model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
        return "/system/user/list";
    }

    /**
     * 查询列表
     */
    @RequestMapping("/lists")
    public void lists(UserParams userParams, Page page, Model model) {

        Table table = userService.queryUserTables(userParams, page);
        model.addAttribute("usersTable", table);
        model.addAttribute("userParams", userParams);
        model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
        model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
        model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));

    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(UserParams userParams, Page page, Model model) {
        try {
            list(userParams, page, model);
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
            model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }


    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            User user = new User();
            model.addAttribute("user", user);
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
            model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            User user = userService.getUser(id);
            model.addAttribute("user", user);
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
            model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteUser(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            userService.deleteUserBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveUser(@Valid User user, BindingResult result) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            if (user.getId() == null) {
                Optional<JsonResponse<String>> optional = userService.checkLoginNameRepeat(user);
                if (optional.isPresent()) {
                    return optional.get().toString();
                }
            }
            userService.saveUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据User保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 跳转到密码修改界面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/goModifyPassword")
    @ResponseBody
    public String goModifyPassword(Integer id, Model model) {
        try {
            User user = userService.getUser(id);
            model.addAttribute("user", user);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/modifyPassword", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 密码修改
     *
     * @return
     */
    @RequestMapping("/modifyPasswordAdmin")
    @ResponseBody
    public String modifyPasswordAdmin(@Valid ModifyPassword modifyPassword, BindingResult result) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            if (!modifyPassword.getPassword1().equals(modifyPassword.getPassword2())) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "两次密码不一致").toString();
            }

            User user = new User();
            user.setId(modifyPassword.getId());
            user.setPassword(DigestUtils.md5Hex(modifyPassword.getPassword1()));
            userService.saveUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户密码修改保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 密码修改
     *
     * @param modifyPassword
     * @param result
     * @param request
     * @return
     */
    @RequestMapping("/modifyPassword")
    @ResponseBody
    public String modifyPassword(@Valid ModifyPassword modifyPassword, BindingResult result, HttpServletRequest request) {

        try {

            User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
            if (user == null) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "您尚未登录，不能进行操作").toString();
            }
            if (StringUtils.isBlank(modifyPassword.getPassword())) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "原始密码不能为空").toString();
            }
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            if (!modifyPassword.getPassword1().equals(modifyPassword.getPassword2())) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "两次密码不一致").toString();
            }

            if (!user.getPassword().equals(DigestUtils.md5Hex(modifyPassword.getPassword()))) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "原始密码不正确").toString();
            }
            user.setPassword(DigestUtils.md5Hex(modifyPassword.getPassword1()));
            userService.saveUser(user);
            request.getSession().setAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME, user);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户密码修改保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 跳转到角色分配页面
     *
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping("/goAssign")
    @ResponseBody
    public String goAssign(String userId, Model model) {
        try {
            List assignRoleList = userRoleService.queryUserRoleByUserId(userId);
            List roleList = roleService.queryRoleList(new RoleParams());
            model.addAttribute("assignRoleList", assignRoleList);
            model.addAttribute("roleList", roleList);
            model.addAttribute("userId", userId);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/assignRole", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 分配用户角色
     *
     * @param userId
     * @param ids
     * @return
     */
    @RequestMapping("/assignRole")
    @ResponseBody
    public String assignRole(String userId, @RequestParam(value = "roleIds", required = false) String[] ids) {

        try {
            userRoleService.assignRole(userId, ids);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户角色分配保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 选择用户
     */
    @RequestMapping("/goSelectSaleUser")
    @ResponseBody
    public String goSelectSaleUser(UserParams userParams, String usingOrgId, Page page, Model model) {
        try {
            OrganizationParams organizationParams = new OrganizationParams();
            List<Organization> allOrgList = organizationService.queryOrganizationTable(organizationParams);
            String parentOrgId = StringUtils.isEmpty(userParams.getOrgId()) ? ShmsConstant.ORG_CACHE : userParams.getOrgId();
            List orgList = organizationService.getOrgList(parentOrgId, allOrgList);
            Organization organization = organizationService.getOrganization(parentOrgId);
            page.setPageSize(6);
            if (organization != null) {
                model.addAttribute("organization", organization);
            }
            if (usingOrgId != null) {
                Organization noworg = organizationService.getOrganization(usingOrgId);
                userParams.setOrgLevelCode(noworg.getOrgLevelCode());
            }

            list(userParams, page, model);
            model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
            model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
            model.addAttribute("orgList", orgList);
            model.addAttribute("userSearchParams", userParams);
            model.addAttribute("usingOrgId", usingOrgId);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/selectUser", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 选择用户(客户分配)
     */
    @RequestMapping("/goSelectSaleUserByOrgId")
    @ResponseBody
    public String goSelectSaleUserByAssignOrgId(UserParams userParams, Page page, Model model) {
        try {
            OrganizationParams organizationParams = new OrganizationParams();
            Organization organization = organizationService.getOrganization(userParams.getOrgId());
            List<Organization> orgList = new ArrayList<Organization>();
            if (organization != null) {
                model.addAttribute("organization", organization);
            }
            userParams.setOrgLevelCode(organization.getOrgLevelCode());
            list(userParams, page, model);
            model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
            model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
            model.addAttribute("orgList", orgList);
            model.addAttribute("userSearchParams", userParams);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/selectUser", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }


    /**
     * 选择页面异步查询列表(主管数据)
     */
    @RequestMapping("/ajaxSelectOSList")
    @ResponseBody
    public String ajaxSelectOSList(UserParams userParams, Page page, Model model) {
        try {
            page.setPageSize(6);
            listOS(userParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/selectUserTable", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    public void listOS(UserParams userParams, Page page, Model model) {
        Table table = userService.queryOSUserTable(userParams, page);
        model.addAttribute("usersTable", table);
        model.addAttribute("userParams", userParams);
        model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
        model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
        model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
    }

    /**
     * 选择页面异步查询列表
     */
    @RequestMapping("/ajaxSelectList")
    @ResponseBody
    public String ajaxSelectList(UserParams userParams, String orgId, Page page, Model model) {
        try {
            if (StringUtils.isNotEmpty(orgId)) {
                Organization noworg = organizationService.getOrganization(orgId);
                userParams.setOrgLevelCode(noworg.getOrgLevelCode());
            }
            userParams.setOrgId(null);
            page.setPageSize(6);
            list(userParams, page, model);
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
            model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/selectUserTable", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 异步查询列表(客户分配-批量分配)
     */
    @RequestMapping("/ajaxBathSelectList")
    @ResponseBody
    public String ajaxBathSelectList(UserParams userParams, String orgId, Page page, Model model) {
        try {
            if (StringUtils.isNotEmpty(orgId)) {
                userParams.setOrgId(orgId);
            }
            page.setPageSize(6);
            list(userParams, page, model);
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("userTypeList", CodeInfoCache.getCodeInfo(CodeType.USER_TYPE));
            model.addAttribute("userStatusList", CodeInfoCache.getCodeInfo(CodeType.USER_STATUS));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/custManage/customAssign/assignUserTable", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 选择会员
     */
    @RequestMapping("/goSelectIllIndex")
    @ResponseBody
    public String goSelectIllIndex(UserParams userParams, String selectType, Page page, Model model) {
        try {
            page.setPageSize(999);
            lists(userParams, page, model);
            if (StringUtils.isEmpty(selectType)) {//单选
                return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/selectIllIndex", model)).toString();
            } else {//多选
                return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/selectIllIndexs", model)).toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 选择会员查询
     */
    @RequestMapping("/ajaxSelect")
    @ResponseBody
    public String ajaxSelect(UserParams userParams, String selectType, Page page, Model model) {
        try {
            lists(userParams, page, model);
            if (StringUtils.isEmpty(selectType)) {//单选
                return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/selectTable", model)).toString();
            } else {//多选
                return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/user/selectTables", model)).toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

}
